package cn.stylefeng.guns.modular.weixin.utils;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.modular.recy.entity.Region;
import cn.stylefeng.guns.modular.recy.service.RegionService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.beetl.ext.fn.Json;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

public class Utils
{
    public static String getRealPath(final String tarDir) {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            System.out.println("path:" + path.getAbsolutePath());
            final File upload = new File(path.getAbsolutePath(), tarDir);
            if (!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println("upload url:" + upload.getAbsolutePath());
            return upload.getAbsolutePath();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static List<String> splitAreaCode(String areaCode){
        if(StrUtil.isBlank(areaCode)) return Lists.newArrayList();
        int[] splitIndexs = new int[]{2,4,6,9,12};
        int areaCodeLen = StrUtil.length(areaCode);
        int maxIndex = Arrays.binarySearch(splitIndexs, areaCodeLen);
        if(maxIndex<0) return Lists.newArrayList();
        List<String> areaCodeList =new ArrayList<>();
        for(int i=0;i<=maxIndex;i++){
            areaCodeList.add(areaCode.substring(0, splitIndexs[i]));
        }
        return areaCodeList;
    }

    public static String areaFullName(String areaCode, RegionService regionService){
        List<String> areaCodeList = splitAreaCode(areaCode);
        if(ObjectUtil.length(areaCodeList)==0){
            return "";
        }else{
            QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<Region>();
            regionQueryWrapper.lambda().in(Region::getLongcode,areaCodeList).orderByAsc(Region::getLevel);
            List<Region> regionList = regionService.list(regionQueryWrapper);
            return Joiner.on("/").join(regionList.stream().map(Region::getName).collect(Collectors.toList()));
        }
    }
    public static String getJarRoot(){
        ApplicationHome home = new ApplicationHome(Utils.class);
        File jarFile = home.getSource();
        return jarFile.getParentFile().getPath();
    }
    public static boolean isRunInJar(){
        String classPath = ClassUtil.getClassPath();
        System.out.println("classPath:"+classPath);
        return classPath==null?true:classPath.contains(".jar!");
    }

    /**
     * 用于请求第三方接口，我们使用的是http请求,请求的数据格式是
     * @param url
     *
     */
    public static JSONObject doGet(String url) {
        JSONObject result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            response = httpClient.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if (status ==HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                }
            }else{
                //不推荐使用CloseableHttpResponse.close关闭连接，他将直接关闭Socket，导致长连接不能复用
                EntityUtils.consume(response.getEntity());
            }
        } catch (IOException e) {
            try {
                if(null !=response )
                    EntityUtils.consume(response.getEntity());
            } catch (IOException e1) {
            }
        }
        return result;
    }


    /**
     * 用于请求第三方接口，我们使用的是http请求,请求的数据格式是json
     * @param params
     */
    public static JSONObject doPost(String url,JSONObject params){
        JSONObject result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try{
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            //将参数转化为String
            //httpPost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));//加入参数
            httpPost.setEntity(new StringEntity(params.toJSONString(),Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                HttpEntity entity = response.getEntity();
                if(entity != null){
                    result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                }else{
                    EntityUtils.consume(response.getEntity());
                }
            }
        }catch(IOException e){
            try {
                if(response != null )
                    EntityUtils.consume(response.getEntity());
            } catch (IOException e1) { }
        }
        return result;
    }

}
